<?php
namespace app\index\controller;
use app\index\logic\RegisterLogic;

/**
 * 注册api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/09/06
 * Time: 09:19
 */
class Register extends Base {

    public function __construct(){
        parent::__construct();
        $this->r_logic = new RegisterLogic();
    }

    /**
     * 检查是否注册
     * @return \think\response\Json
     */
    public function ajax_check_is_reg(){
        $params = input();
        $r = $this->check_user_token($params);
        if($r['code'] != 1){
            return json($r);
        }

        //检查用户规则
        $r = $this->r_logic->check_user_rule();
        if($r['code'] != 1){
            return json($r);
        }
        $u_detail = $r['data']['detail'];

        $data['detail'] = $u_detail;
        return json($this->r_logic->get_response(1,'OK',$data));
    }

    /**
     * 注册
     * @return \think\response\Json
     */
    public function ajax_register(){
        $params = input();
        $r = $this->check_user_token($params);
        if($r['code'] != 1){
            return json($r);
        }
        $openid = session('openid');

        //检查注册规则
        $r = $this->r_logic->check_register_rule($params);
        if(!$r['code']){
            return json($r);
        }

        $maps = [];
        $maps[] = ['openid','=',$openid];
        $maps[] = ['role','>',1];
        $u_detail = model('user')->get_detail($maps,'id');
        if(empty($u_detail)){
            $u_data = [];
            $u_data['openid'] = $openid;
            $u_data['username'] = trim($params['username']);
            $u_data['tel'] = trim($params['tel']);
            $u_data['department'] = trim($params['department']);
            $u_data['position'] = trim($params['position']);
            $u_data['use_branchid'] = 1;
            $r = model('user')->insert($u_data);
        }else{
            $u_data = [];
            $u_data['username'] = trim($params['username']);
            $u_data['tel'] = trim($params['tel']);
            $u_data['department'] = trim($params['department']);
            $u_data['position'] = trim($params['position']);
            $u_data['use_branchid'] = 1;
            $u_data['status'] = 0;

            $maps = [];
            $maps[] = ['id','=',$u_detail['id']];
            $r = model('user')->force()->save($u_data,$maps);
        }

        if($r !== false){
            return json($this->r_logic->get_response(1,'注册成功，请等待管理员审核'));
        }
        return json($this->r_logic->get_response(0,'注册失败'));
    }
}
